package com.AnywheeBt;

import java.util.ArrayList;
import java.util.List;


import com.AnywheeBt.bean.AiosContacts;
import com.AnywheeBt.bean.BtContact;
import com.AnywheeBt.bean.ContactInfo;
import com.AnywheeBt.bean.PhoneInfo;
import com.AnywheeBt.bean.Record;
import com.aispeech.aios.client.AIOSContactsNode;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static DatabaseHelper mDatabaseHelper = null;
    public static final String DB_NAME = "phonebook.db";
    public static final String BOOK_TABLE_NAME = "phonebook";
    public static final String RECORD_TABLE_NAME = "phone_record";
    public static final String ID = "_id";
    public static final String BT_ADD = "_address";
    public static final String NAME = "phonename";
    public static final String NUMBER = "phonenumber";
    public static final String SPELL = "namespell";
    public static final String INITAL = "nameinital";
    private static final int VERSION = 1;
    public static final String RECORD_TYPE = "type";
    
    public static final int TYPE_CALL = 1;
    public static final int TYPE_COMING = 2;
    public static final int TYPE_DIS = 3;

	private static List<ContactInfo> mAiosContacts = null;

    private DatabaseHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    public static DatabaseHelper getDatabaseHelper(Context context) {
        if (mDatabaseHelper == null) {
            mDatabaseHelper = new DatabaseHelper(context);
            mAiosContacts = new ArrayList<ContactInfo>();
        }
        return mDatabaseHelper;
    }
    
    public List<ContactInfo> getAiosContacts() {
        if (mAiosContacts == null) {
            mAiosContacts = new ArrayList<ContactInfo>();
        }
        return mAiosContacts;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE IF NOT EXISTS " + BOOK_TABLE_NAME + "(" 
        		+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        		+ BT_ADD + " text,"
        		+ NAME + " text,"	
                + NUMBER + " text)";
        db.execSQL(sql);
        String sql2 = "CREATE TABLE IF NOT EXISTS " + RECORD_TABLE_NAME + "("
                + ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + BT_ADD + " text,"
        		+ NAME + " text,"
                + NUMBER + " text," 
        		+ RECORD_TYPE + " INTEGER)";
        db.execSQL(sql2);
    }

    //
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    //
    public ArrayList<BtContact> queryAllContacts() {
        ArrayList<BtContact> contacts = new ArrayList<BtContact>();
        mAiosContacts.clear();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(BOOK_TABLE_NAME, null, BT_ADD+"=?", new String[]{SzhBAction.GetBtAddress()}, null, null,
                "_id asc");
		Log.i("datahepl","cursor.getCount():"+cursor.getCount());
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(NAME));
                String number = cursor.getString(cursor.getColumnIndex(NUMBER));
                //
                BtContact contact = new BtContact();
                contact.setName(name);
                contact.setNumber(number);
                contacts.add(contact);
                //
                ContactInfo contactInfo = new ContactInfo();
                ContactInfo.PhoneInfo phoneInfo = new ContactInfo.PhoneInfo();
                //
                contactInfo.setName(name);
                phoneInfo.setNumber(number.toString());
                contactInfo.addPhoneInfo(phoneInfo);
                mAiosContacts.add(contactInfo);
            }
        }
        cursor.close();
        return contacts;
    }
     public ArrayList<BtContact> queryPeoplesByName(String name, String s){
         ArrayList<BtContact> contacts = new ArrayList<BtContact>();
         SQLiteDatabase db = getReadableDatabase();
         Cursor cursor = db.query(BOOK_TABLE_NAME, null, BT_ADD+"=? and (" + SPELL + "=? or " + INITAL + "=?)", new String[]{SzhBAction.GetBtAddress(), name, s}, null, null,
                 "_id asc");
         Log.i("datahepl","cursor.getCount():"+cursor.getCount());
         if (cursor.getCount() > 0) {
             while (cursor.moveToNext()) {
                 String pname = cursor.getString(cursor.getColumnIndex(NAME));
                 String pnumber = cursor.getString(cursor.getColumnIndex(NUMBER));
				 String nameSpell = cursor.getString(cursor.getColumnIndex(SPELL));
                 BtContact contact = new BtContact();
                 contact.setName(pname);
                 contact.setNumber(pnumber);
				 contact.setNameSpell(nameSpell);
                contacts.add(contact);
            }
        }
        cursor.close();
        return contacts;
    }
    //
    public ArrayList<Record> queryAllRecords() {
        ArrayList<Record> records = new ArrayList<Record>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(RECORD_TABLE_NAME, null,BT_ADD+"=?", new String[]{SzhBAction.GetBtAddress()}, null,
                null, "_id desc");
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(ID));
                String name = cursor.getString(cursor.getColumnIndex(NAME));
                String number = cursor.getString(cursor.getColumnIndex(NUMBER));
                int type = cursor.getInt(cursor.getColumnIndex(RECORD_TYPE));
                Record record = new Record();
                record.setId(id);
                record.setName(name);
                record.setNumber(number);
                record.setType(type);
                records.add(record);
            }
        }
        cursor.close();
        return records;
    }

    public long insertContact(String command) {
        SQLiteDatabase db = getWritableDatabase();
        int type;
        int nameLen;
        int numLen;
        String name;
        String num;
        type = Integer.parseInt(command.substring(2, 3));
        if (type != 0 && type != 1) {
            return -1;
        }
        nameLen = Integer.parseInt(command.substring(3, 5));
        numLen = Integer.parseInt(command.substring(5, 7));
        
        if(command.length() > numLen+6){
        	num = command.substring(command.length() - numLen);
    		name= command.substring(7,command.length() - numLen);
    	}else{
    		name = command.substring(7, 7 + nameLen / 3);
            num = command.substring(7 + nameLen / 3, command.length());
    	}        
        if (num.length()==0 || isNumberExist(num)) {
            return -1;
        }
        ContentValues contentValues = new ContentValues();
        contentValues.put(BT_ADD, SzhBAction.GetBtAddress());
        contentValues.put(NAME, name);
        contentValues.put(NUMBER, num);
        return db.insert(BOOK_TABLE_NAME, null, contentValues);

    }
    
    public long insertContact(String addr,String name,String number) {
			SQLiteDatabase db = getWritableDatabase();


        if (number.length()==0 || isNumberExist(number)) {
            return -1;
        }

        ContentValues contentValues = new ContentValues();
        contentValues.put(BT_ADD, addr);
        contentValues.put(NAME, name);
        contentValues.put(NUMBER, number);
        return db.insert(BOOK_TABLE_NAME, null, contentValues);

    }
    
    public boolean isNumberExist(String num){
    	SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(BOOK_TABLE_NAME, null,BT_ADD+"=? and " + NUMBER + "=?", new String[]{SzhBAction.GetBtAddress(),num}, null,
                null, "_id desc");
        if(cursor.getCount()>0)	return true;
    	return false;
    }
    
    public String getNameByNum(String num){
    	String name="";
    	SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(BOOK_TABLE_NAME, null,BT_ADD+"=? and " + NUMBER + "=?", new String[]{SzhBAction.GetBtAddress(),num}, null,
                null, "_id desc");
        if(cursor.getCount()>0){
        	while (cursor.moveToNext()) {
        		name = cursor.getString(cursor.getColumnIndex(NAME));
            }
        }
    	return name;
    }

    public long insertRecord(Record record) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(BT_ADD, SzhBAction.GetBtAddress());
        contentValues.put(NAME, record.getName());
        contentValues.put(NUMBER, record.getNumber());
        contentValues.put(RECORD_TYPE, record.getType());
        return db.insert(RECORD_TABLE_NAME, null, contentValues);
    }

    public void deleNumber(String number) {
        SQLiteDatabase db = getWritableDatabase();
		Log.i("datahepl","deleNumber:"+number);
        db.delete(BOOK_TABLE_NAME, NUMBER+"=? and " + BT_ADD + "=?",new String[]{number,SzhBAction.GetBtAddress()});
    }

    public void deleRecord(Record record) {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(RECORD_TABLE_NAME, " " + ID + " = ? ",
                new String[] { record.getId() + "" });
    }
    
    public void delTopRecord(String num) {
    	SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(RECORD_TABLE_NAME, null,
        		BT_ADD+"=? and " + NUMBER + "=? and " + RECORD_TYPE + "=? ", 
        		new String[]{SzhBAction.GetBtAddress(),num,TYPE_DIS+""}, null,
                null, "_id desc");
        if(cursor.getCount()>0){
        	cursor.moveToFirst();
        	int id = cursor.getInt(cursor.getColumnIndex(ID));
        	db.delete(RECORD_TABLE_NAME, " " + ID + " = ? ",
                    new String[] { id + "" });
        }
    }

    public void delAllNumber() {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(BOOK_TABLE_NAME, ID+">=? and " + BT_ADD + "=?",new String[]{"0",SzhBAction.GetBtAddress()});
    }

    public void delAllRecord() {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(RECORD_TABLE_NAME, ID+">=? and " + BT_ADD + "=?",new String[]{"0",SzhBAction.GetBtAddress()});
    }
}
